<?php

namespace app\index\controller;

class Index
{
    public function index()
    {
        $request = request();
        $code = $request->get("code");
        $appid = "wx5cd58f947a53db52";
        $appSecret = "06cef7b723db7f3ba9447dc7f700f34a";
        if (!$code) {
            $site = "http://test.yingqutv.com";
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$site&response_type=code&scope=snsapi_userinfo&connect_redirect=1&state=1";
            return redirect($url);
        }

        $api = new \Gaoming13\WechatPhpSdk\Api(
            array(
                'appId' => $appid,
                'appSecret' => $appSecret,
                'get_access_token' => function () {
                    // 用户需要自己实现access_token的返回
                    return json_decode(get_php_file("access_token.php"));;
                },
                'save_access_token' => function ($token) {
                    // 用户需要自己实现access_token的保存
                    set_php_file("access_token.php", json_encode($token));
                }
            )
        );

        header('Content-type: text/html; charset=utf-8');

        list($err, $user_info) = $api->get_userinfo_by_authorize('snsapi_userinfo');

        if ($user_info !== null) {
            $openId = $user_info->openid;
            $nickname = $user_info->nickname;
            $headimgurl = $user_info->headimgurl;
            session("openid", $openId);
            session("nickname", $nickname);
            session("headimgurl", $headimgurl);
        } else {
            echo '授权失败111！';
        }
        if (session("openid")) {
            /*查询用户是否已经登陆过*/
            $query = model("User")->where("openid", "=", session("openid"))->find();
            if ($query) {
                // 获取 手机 姓名
                $mobile = $query["mobile"];
                $username = $query["nickname"];
                $data = [
                    "isregister" => "true",
                    "mobile" => $mobile,
                    "username" => "$username",
                ];
                session("openid", $query["openid"]);
                return view('index/index', ["data" => $data]);
            } else {
                //第一次登陆
                $data = [
                    "openid" => session("openid"),
                    "nickname" => session("nickname"),
                    "headimg" => session("headimgurl"),
                ];
                session("openid", session("openid"));
                $save = model("User")->save($data);
                if ($save) {
                    $data = [
                        "isregister" => "false",
                        "mobile" => "",
                        "username" => "",
                    ];
                    return view('index/index', ["data" => $data]);
                } else {
                    echo '授权失败！';
                }
            }
        }

    }

    public function saveUserInfo()
    {
        $request = request();
        $name = $request->post("username");
        $mobile = $request->post("mobile");
        if ($name && $mobile) {
            $search = '/^0?1[3|4|5|6|7|8][0-9]\d{8}$/';
            if ( preg_match( $search, $mobile ) ) {
                $data = [
                    "name" => $name,
                    "mobile" => $mobile,
                ];
                $openid = session("openid");
                if ($openid) {
                    $save = model("User")->where("openid", "=", $openid)->update($data);
                    if ($save) {
                        return json([
                            "code" => 200,
                            "msg" => "",
                            "data" => "",
                        ]);
                    }
                } else {
                    return json([
                        "code" => 400,
                        "msg" => "请重新登陆",
                        "data" => "",
                    ]);
                }
            } else {
                return json([
                    "code" => 400,
                    "msg" => "请填写正确的手机号",
                    "data" => "",
                ]);
            }
        } else {
            return json([
                "code" => 400,
                "msg" => "请填写完整信息",
                "data" => "",
            ]);
        }
    }

    public function pushScore()
    {
        $request = request();
        $score = $request->post("score");
        $openid = session("openid");
        if ($openid) {
            $save = model("User")->where("openid", "=", $openid)->update(["score" => $score]);
            if ($save) {
                $ret=[];
                $query = model("User")->order("score desc")->limit(5)->select();
                $i=1;
                $has=false;
                foreach ($query as $item){
                    $one=[
                        "rank"=>$i,
                        "username"=>$item["name"],
                        "weixinname"=>$item["nickname"],
                        "avatar"=>$item["headimg"],
                        "score"=>$item["score"],
                        "mobile"=>$item["mobile"],
                    ];
                    array_push($ret,$one);
                    if($item["openid"]==$openid){
                        $has=true;
                    }else{
                        if($has){
                            continue;
                        }
                    }
                    $i++;
                }
                if($has){
                    return json([
                        "code" => 200,
                        "msg" => "",
                        "data" =>$ret,
                    ]);
                }else{
                    return json([
                        "code" => 200,
                        "msg" => "",
                        "data" =>$ret,
                    ]);
                }

            }
        } else {
            return json([
                "code" => 400,
                "msg" => "请重新登陆",
                "data" => "",
            ]);
        }
    }
}
